package com.ketai.service.impl;

import cn.hutool.core.util.StrUtil;
import com.aliyun.credentials.utils.StringUtils;
import com.ketai.common.KetaiException;
import com.ketai.common.MessageConstant;
import com.ketai.common.StatusCode;
import com.ketai.dao.ActivityDao;
import com.ketai.dao.impl.ActivityDaoImpl;
import com.ketai.pojo.CActivity;
import com.ketai.query.ActivitesQuery;
import com.ketai.service.ActivityService;
import com.ketai.util.Pages;
import com.ketai.vo.ActivityVo;

import javax.naming.NamingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:长沙科泰梦想学院-蓝色小药丸
 * @Mission:打造演说·创客型跨境电商与互联网人才
 * @Description:
 * @Date:Create In 2022/8/4 22:20
 **/
public class ActivityServiceImpl implements ActivityService {

    ActivityDao activityDao = new ActivityDaoImpl();

    @Override
    public Pages<ActivityVo> getAllActivities (ActivitesQuery query) {
        Pages<ActivityVo> result = new Pages<ActivityVo>();

        // 封装查询条件的参数
        List params = new ArrayList();
        StringBuilder sql = new StringBuilder("SELECT  b.* , u.name checkedName  from  (select a.checkedId,  a.id, t.name typeName,  o.name pbName, a.title, a.time ,a.position ,a.apply_time, ");
        sql.append("    a.apply_end_time,a.apply_people_num, a.checked ,a.checked_time from c_activity a , organizationbase  o ,activity_type t ");
        sql.append("   where  a.tid=t.id and  a.pbid=o.id  ");

        // 查询符合条件的总页数
        StringBuilder sql2 = new StringBuilder(" select  count(1) total  from c_activity a , organizationbase  o , activity_type t  where  a.tid=t.id and  a.pbid=o.id ");
       // 动态条件判断  StrUtil   huTool中的String工具类
        if (!StrUtil.hasEmpty(query.getTitle())) {
                sql.append(" and b.title like concat('%',?,'%') ");
               sql2.append(" and b.title like concat('%',?,'%') ");
                params.add(query.getTitle());

        }
        if (!StrUtil.hasEmpty(query.getStartTime())) {
            sql.append(" and b.time >=? ");
            sql2.append(" and b.time >=? ");
            params.add(query.getStartTime());
        }
        if (!StrUtil.hasEmpty(query.getEndTime())) {
            sql.append(" and b.time<=? ");
            sql2.append(" and b.time<=? ");
            params.add(query.getEndTime());
        }

        if (!StrUtil.hasEmpty(query.getType())) {
            sql.append(" and tid=? ");
            sql2.append(" and tid=? ");
            params.add(query.getType());
        }

        if (!StrUtil.hasEmpty(query.getChecked())) {
            sql.append(" and checked=? ");
            sql2.append(" and checked=? ");
            params.add(query.getChecked());
        }
        sql.append("  ) b  left join  background_user u on u.id= checkedId  ");
        try {
            long total = activityDao.getTotalActivityCount(sql2.toString(), params.toArray());
            result.setDataTotal(total);


             Integer pageSize=Integer.parseInt(query.getLimit());
             result.setPageNumber(pageSize);
             Integer pageNo=Integer.parseInt(query.getCurr());
            // 获取总页数  计算出总页数
            int pages = (int) (total % pageSize == 0 ? total / pageSize : total / pageSize + 1);
            result.setTotalPages(pages);
            // 处理当前页码的问题   如果传过来的当前页大于总页数  赋值为总页数
            pageNo = pageNo > pages ? pages : pageNo;
            // 如果当前页小于第一页 赋值为第一页
            pageNo = pageNo <= 0 ? 1 : pageNo;
            //设置当前页面
            result.setCurrentPage(pageNo);
            // 分页查询
            sql = sql.append("  order by b.id desc   limit ?,? ");
            params.add((pageNo - 1) * pageSize);
            params.add( pageSize);
            List<ActivityVo> allActivities = activityDao.getAllActivities(sql.toString(), params.toArray());
            result.setDataItems(allActivities);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return result;
    }


    @Override
    public Pages<ActivityVo> getAllEndActivities (ActivitesQuery query) {
        Pages<ActivityVo> result = new Pages<ActivityVo>();

        // 封装查询条件的参数
        List params = new ArrayList();
        StringBuilder sql = new StringBuilder("SELECT  b.* , u.name checkedName  from  (select a.checkedId,  a.id, t.name typeName,  o.name pbName, a.title, a.time ,a.position ,a.apply_time, ");
        sql.append("    a.apply_end_time,a.apply_people_num, a.checked ,a.checked_time from c_activity a , organizationbase  o ,activity_type t where date_format(a.time,'%Y-%m-%d') < date_format(now(),'%Y-%m-%d') ");
        sql.append("   and   a.tid=t.id and  a.pbid=o.id  ");

        // 查询符合条件的总页数
        StringBuilder sql2 = new StringBuilder(" select  count(1) total  from c_activity a , organizationbase  o , activity_type t  where  a.tid=t.id and  a.pbid=o.id and date_format(a.time,'%Y-%m-%d') < date_format(now(),'%Y-%m-%d')");
        // 动态条件判断  StrUtil   huTool中的String工具类
        if (!StrUtil.hasEmpty(query.getTitle())) {
            sql.append(" and title like concat('%',?,'%') ");
            sql2.append(" and title like concat('%',?,'%') ");
            params.add(query.getTitle());

        }
        if (!StrUtil.hasEmpty(query.getStartTime())) {
            sql.append(" and time >=? ");
            sql2.append(" and time >=? ");
            params.add(query.getStartTime());
        }
        if (!StrUtil.hasEmpty(query.getEndTime())) {
            sql.append(" and time<=? ");
            sql2.append(" and time<=? ");
            params.add(query.getEndTime());
        }

        sql.append("  ) b  left join  background_user u on u.id= checkedId  ");
        try {
            long total = activityDao.getTotalActivityCount(sql2.toString(), params.toArray());
            result.setDataTotal(total);


            Integer pageSize=Integer.parseInt(query.getLimit());
            result.setPageNumber(pageSize);
            Integer pageNo=Integer.parseInt(query.getCurr());
            // 获取总页数  计算出总页数
            int pages = (int) (total % pageSize == 0 ? total / pageSize : total / pageSize + 1);
            result.setTotalPages(pages);
            // 处理当前页码的问题   如果传过来的当前页大于总页数  赋值为总页数
            pageNo = pageNo > pages ? pages : pageNo;
            // 如果当前页小于第一页 赋值为第一页
            pageNo = pageNo <= 0 ? 1 : pageNo;
            //设置当前页面
            result.setCurrentPage(pageNo);
            // 分页查询
            sql = sql.append("  order by b.time desc   limit ?,? ");
            params.add((pageNo - 1) * pageSize);
            params.add( pageSize);
            List<ActivityVo> allActivities = activityDao.getAllActivities(sql.toString(), params.toArray());
            result.setDataItems(allActivities);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public int addActivity (CActivity activity) throws KetaiException {
        int result=0;
        try {
           result = activityDao.addActivity(activity);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new KetaiException(StatusCode.ERROR, MessageConstant.ACTITY_SAVE_ERROR);
        } catch (NamingException e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    public int deleteActivityById (String id) {
        int result = 0;
        try {
            result=activityDao.deleteActivityById(id);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public int editActivity (CActivity activity) {
        return 0;
    }

    @Override
    public ActivityVo getActivityById (String id) {
        try {
            return activityDao.getActivityById(id);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (NamingException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public int checkedActity (String id, String open, String desc,String checkedId) {
        String sql="update c_activity set checked=? ";
        List params = new ArrayList();
          if (!StrUtil.isBlank(open)&&open.equals("on")) {
               params.add(1);
          }else {
              sql+=" ,  `desc`=? ";
              params.add(2);
              params.add(desc);
          }
          sql += " , checked_time=now() ,checkedId=? where id=?";
        params.add(checkedId);
          params.add(id);
        System.out.println(sql);
        try {
           return  activityDao.checkedActity(sql, params.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
